package net.oschina.archx.spring.web;

import net.oschina.archx.spring.Application;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;

/**
 * DownloadController
 *
 * @author Archx[archx@foxmail.com]
 * @date 2016/2/25 0025
 */
@Controller
@RequestMapping("/download")
public class DownloadController {

    /**
     * 根据请求头判断浏览器处理文件名
     *
     * @param userAgent
     * @return
     */
    @RequestMapping
    public ResponseEntity<byte[]> index(@RequestHeader("user-agent") String userAgent) throws IOException {
        String path = Application.getRealPath("/") + "test.txt";
        File file = new File(path);

        FileInputStream in = new FileInputStream(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = in.read(buff)) != -1)
            out.write(buff, 0, len);
        // 下载
        byte[] bytes = out.toByteArray();
        String fileName = "测试文件.txt";
        // 文件名问题
        if (userAgent.contains("MSIE")) { // IE
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else { // FF,Chrome..
            fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        }
        HttpHeaders headers = new HttpHeaders();
        headers.set(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
    }
}
